#20250613 尤文杰
import tkinter as tk
import random

# 生成随机谜底
secret_number = random.randint(1, 200)
attempts_list = []  # 记录用户的有效尝试
attempts_count = 0  # 记录有效尝试的次数

# 游戏逻辑
def check_guess():
    global attempts_count
    try:
        guess = int(entry.get())  # 获取用户输入的数字
        if guess < 1 or guess > 200:
            result_label.config(text="请输入 1 到 200 之间的数字！", fg="red")
        elif guess < secret_number:
            result_label.config(text="小了，再试试！", fg="blue")
            record_attempt(guess)  # 记录用户尝试的数字
        elif guess > secret_number:
            result_label.config(text="大了，再试试！", fg="blue")
            record_attempt(guess)
        else:
            record_attempt(guess)  # 记录最后一次猜测
            result_label.config(text=f"🎉 恭喜！猜对了！答案是 {secret_number} 🎉", fg="green")
            entry.config(state="disabled")  # 禁用输入框
            guess_button.config(state="disabled")  # 禁用按钮
    except ValueError:
        result_label.config(text="❌ 请输入有效数字！", fg="red")

# 记录用户输入的数字
def record_attempt(guess):
    global attempts_count
    if guess not in attempts_list:  # 防止重复输入
        attempts_list.append(guess)
        attempts_count += 1
        history_label.config(text=f"尝试过的数字：{attempts_list}")
        count_label.config(text=f"有效尝试次数：{attempts_count}")

# 重新开始游戏
def restart_game():
    global secret_number, attempts_list, attempts_count
    secret_number = random.randint(1, 200)  # 重新生成数字
    attempts_list = []  # 清空记录
    attempts_count = 0
    result_label.config(text="请输入 1-100 之间的数字进行猜测", fg="black")
    entry.delete(0, tk.END)  # 清空输入框
    history_label.config(text="尝试过的数字：")  # 重置历史记录
    count_label.config(text="有效尝试次数：0")  # 重置次数
    entry.config(state="normal")  # 禁用输入框
    guess_button.config(state="normal")  # 禁用按钮

# 创建窗口
root = tk.Tk()
root.title("猜数字游戏 - 记录版")
root.geometry("400x350")

# 标题标签
title_label = tk.Label(root, text="🎯 猜 1 - 200 之间的数字 🎯", font=("Arial", 14))
title_label.pack(pady=10)

# 结果显示标签
result_label = tk.Label(root, text="请输入 1-200 之间的数字进行猜测", font=("Arial", 12))
result_label.pack()

# 用户输入框
entry = tk.Entry(root, font=("Arial", 14))
entry.pack(pady=10)

# 按钮框架
button_frame = tk.Frame(root)
button_frame.pack()

# 猜测按钮
guess_button = tk.Button(button_frame, text="猜一猜", command=check_guess, font=("Arial", 12))
guess_button.grid(row=0, column=0, padx=5)

# 重新开始按钮
restart_button = tk.Button(button_frame, text="重新开始", command=restart_game, font=("Arial", 12))
restart_button.grid(row=0, column=1, padx=5)

# 显示尝试的历史记录
history_label = tk.Label(root, text="尝试过的数字：", font=("Arial", 10))
history_label.pack(pady=5)

# 显示有效尝试次数
count_label = tk.Label(root, text="有效尝试次数：0", font=("Arial", 10))
count_label.pack(pady=5)

# 运行 Tkinter 主循环
root.mainloop()
